<script setup>
import { nextTick, reactive, ref } from 'vue'
import { storeToRefs } from 'pinia'
import useRoleStore from '@/store/role/index.js'
import useLoginStore from '@/store/user/index.js'
import useMenuStore from '@/store/menu/index.js'
import { generateTree, treeChildren } from '@/utils/treeUtils.js'

const loginStore = useLoginStore()
const menuStore = useMenuStore()
const roleStore = useRoleStore()
const { menuTree } = storeToRefs(menuStore)

//dialog显示
const dialogVisible = ref(false)

//添加用户表单
const addForm = reactive({
  roleId: '',
  roleName: '',
  roleKey: '',
  status: '0',
  menuIds: '',
  remark: '',
  value: ''
})

//校验规则
const formRef = ref()
const rules = reactive({
  roleName: [{ required: true, message: '角色不能为空', trigger: 'blur' }],
  roleKey: [{ required: true, message: '权限字符不能为空', trigger: 'blur' }]
})

//判断操作方法，true新增
const isNewOrUpdate = ref(true)
const isNewOrUpdateTitle = ref('新增角色')

//操作信息
const dialogConfirmBtn = async () => {
  //判断新增还是修改
  //新增，清除组件残留内容，检验表单
  if (isNewOrUpdate.value) {
    await formRef.value.validate()
    //保存信息
    await roleStore.addRoleAction(addForm)
  } else {
    if (!addForm.menuIds) {
      // 当前菜单没有变化
      addForm.menuIds = addForm.menus.map((item) => item.menuId)
    }
    //修改
    await roleStore.editRoleAction(addForm)
  }
  //关闭弹窗
  dialogVisible.value = false
  //清除表单内容
  formRef.value.resetFields()
  //刷新数据
  roleStore.getRoleListAction(1, 10)
}

//编辑回显信息
const treeRef = ref()
const dialogEditInfoBtn = (data) => {
  console.log('data:', data)
  //获取选中的树节点最后一级
  const menuIdsMap = [...data.menus]
  const menuTree = generateTree(menuIdsMap)
  nextTick(() => {
    const ids = treeChildren(menuTree)
    treeRef?.value.setCheckedKeys(ids)
  })
  isNewOrUpdateTitle.value = '编辑角色'
  //调用接口展示角色信息
  Object.assign(addForm, data)
}

//关闭dialog清除信息
const removeDialog = ref(true)
const closeDialogBtn = () => {
  //清除校验信息
  formRef.value.resetFields()
  treeRef?.value.setCheckedKeys([])
  Object.assign(addForm, {
    roleId: '',
    roleName: '',
    roleKey: '',
    status: '0',
    menuIds: '',
    remark: '',
    value: ''
  })
}

//获取选中节点的数据
const menuIdsStore = ref([])
const chooseNode = (value1, value2) => {
  //先移除原有数据
  menuIdsStore.value = []
  menuIdsStore.value.push(...value2.checkedKeys)
  menuIdsStore.value.push(...value2.halfCheckedKeys)
  addForm.menuIds = menuIdsStore.value
}

//对外暴露方法
defineExpose({
  dialogVisible,
  dialogConfirmBtn,
  dialogEditInfoBtn,
  isNewOrUpdate,
  removeDialog
})
</script>

<template>
  <div class="dialog">
    <el-dialog
      v-if="removeDialog"
      @close="closeDialogBtn"
      v-model="dialogVisible"
      :title="isNewOrUpdateTitle"
      width="500px"
    >
      <el-form ref="formRef" :rules="rules" :model="addForm">
        <el-form-item label="角色名称" prop="roleName" label-width="80px">
          <el-input v-model="addForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="权限字符" label-width="80px" prop="roleKey">
          <el-input v-model="addForm.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="状态" label-width="80px">
          <el-select
            v-model="addForm.status"
            placeholder="请选择状态"
            size="large"
            style="width: 179px"
          >
            <el-option value="0" label="启用" />
            <el-option value="1" label="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单权限" label-width="80px">
          <el-tree
            ref="treeRef"
            style="width: 179px"
            :data="menuTree"
            show-checkbox
            node-key="value"
            @check="chooseNode"
          />
        </el-form-item>
        <el-form-item label="备注" label-width="80px" style="width: 100%">
          <el-input v-model="addForm.remark" placeholder="请选择备注" type="textarea" />
        </el-form-item>
      </el-form>
      <!--      底部-->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="dialogConfirmBtn"> 确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.dialog {
  .el-form {
    margin-left: 30px;
    margin-top: 30px;
  }

  .el-form-item {
    font-weight: 700;
  }
}
</style>
